(() => {
  const $ = (sel) => document.querySelector(sel);
  const messagesEl = $("#messages");
  const statusEl = $("#status");
  const wsUrlEl = $("#wsUrl");
  const connectBtn = $("#connectBtn");
  const disconnectBtn = $("#disconnectBtn");
  const roomInput = $("#nickname");   // 复用为“房间号”输入框
  const roomBtn = $("#joinBtn");      // 复用为“进入房间”按钮
  const autoScrollEl = $("#autoScroll");
  const inputEl = $("#messageInput");
  const sendBtn = $("#sendBtn");

  // 状态
  let ws = null;
  let nickname = "";           // 登录页设置
  let reconnectTimer = null;
  let currentRoom = "";        // 当前房间
  let wantConnect = true;      // 期望保持连接
  let wantRoom = "";           // 期望加入的房间（用于重连后自动JOIN）

  // 未登录跳回登录页
  (function guardAuth(){
    const ok = localStorage.getItem('authOK') === '1';
    if(!ok){
      try { window.location.replace('/'); } catch(_) { window.location.href = '/'; }
      return;
    }
  })();

  // 初始化身份与UI文案
  (function initIdentity(){
    nickname = (localStorage.getItem('nickname') || '').trim();
    currentRoom = (localStorage.getItem('roomId') || '').trim();
    if (roomInput) {
      roomInput.placeholder = "输入房间号";
      if (currentRoom) roomInput.value = currentRoom;
    }
    if (roomBtn) roomBtn.textContent = "进入房间";
    // 地址框与连接按钮对用户可见但不必操作，自动连接
  })();

  function setStatus(state, text){
    statusEl.className = `status status-${state}`;
    statusEl.textContent = text;
  }

  function ts(){
    const d = new Date();
    const pad = (n) => String(n).padStart(2,'0');
    return `${d.getHours()}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  }

  function addMeta(text){
    const li = document.createElement("li");
    li.className = "msg meta";
    const bubble = document.createElement("div");
    bubble.className = "bubble";
    bubble.textContent = `[${ts()}] ${text}`;
    li.appendChild(bubble);
    messagesEl.appendChild(li);
    scrollMaybe();
  }

  function addMsg(sender, text, self=false){
    const li = document.createElement("li");
    li.className = "msg" + (self ? " self" : "");
    const bubble = document.createElement("div");
    bubble.className = "bubble";
    bubble.textContent = (sender ? `${sender}: ` : "") + text;
    const meta = document.createElement("div");
    meta.className = "meta";
    meta.textContent = ts();
    if(self){
      li.appendChild(meta);
      li.appendChild(bubble);
    } else {
      li.appendChild(bubble);
      li.appendChild(meta);
    }
    messagesEl.appendChild(li);
    scrollMaybe();
  }

  function scrollMaybe(){
    if(autoScrollEl && autoScrollEl.checked){
      messagesEl.parentElement.scrollTop = messagesEl.parentElement.scrollHeight;
    }
  }

  function resolveWsUrl(){
    // 优先用输入框；否则自动使用当前页面 host:port
    const manual = wsUrlEl && wsUrlEl.value ? wsUrlEl.value.trim() : "";
    if (manual) return manual;
    const isHttps = window.location.protocol === 'https:';
    const wsScheme = isHttps ? 'wss' : 'ws';
    const autoUrl = wsScheme + '://' + window.location.host;
    if (wsUrlEl) wsUrlEl.value = autoUrl;
    return autoUrl;
  }

  function enableSendIfReady(){
    const ok = ws && ws.readyState === WebSocket.OPEN && !!currentRoom;
    inputEl.disabled = !ok;
    sendBtn.disabled = !ok;
    if (!ok) {
      if (!ws || ws.readyState !== WebSocket.OPEN) {
        setStatus("disconnected", "未连接");
      } else if (!currentRoom) {
        setStatus("connected", "未加入房间");
      }
    } else {
      setStatus("connected", `已连接（房间：${currentRoom}）`);
    }
  }

  function connect(){
    const url = resolveWsUrl();
    try{
      setStatus("connecting", "连接中...");
      ws = new WebSocket(url);
    } catch(err){
      setStatus("disconnected", "连接失败");
      addMeta("创建 WebSocket 失败: " + err.message);
      scheduleReconnect();
      return;
    }

    ws.onopen = () => {
      addMeta("已连接到 " + url);
      if (connectBtn) connectBtn.disabled = true;
      if (disconnectBtn) disconnectBtn.disabled = false;

      // 同步昵称
      if (nickname){
        try { ws.send("NICK:" + nickname); } catch(_) {}
        addMeta(`已登录，昵称：${nickname}`);
      }

      // 若期望房间存在，则自动 JOIN
      const toJoin = wantRoom || currentRoom;
      if (toJoin){
        try { ws.send("JOIN:" + toJoin); } catch(_) {}
        addMeta(`加入房间：${toJoin}`);
        currentRoom = toJoin;
        localStorage.setItem('roomId', currentRoom);
      } else {
        addMeta("请输入房间号并点击“进入房间”");
      }

      enableSendIfReady();
    };

    ws.onmessage = (ev) => {
      let text = "";
      try{
        text = typeof ev.data === "string" ? ev.data : "[二进制数据]";
      }catch(_){
        text = "[收到消息]";
      }
      // 服务端已基于房间广播，这里直接展示“昵称: 内容”
      const idx = text.indexOf(": ");
      if(idx > 0){
        const sender = text.slice(0, idx);
        const body = text.slice(idx + 2);
        addMsg(sender, body, false);
      }else{
        addMeta(text);
      }
    };

    ws.onerror = () => {
      addMeta("连接错误");
    };

    ws.onclose = () => {
      addMeta("连接已关闭");
      if (connectBtn) connectBtn.disabled = false;
      if (disconnectBtn) disconnectBtn.disabled = true;
      enableSendIfReady();
      if (wantConnect) scheduleReconnect();
    };
  }

  function scheduleReconnect(){
    if(reconnectTimer) clearTimeout(reconnectTimer);
    reconnectTimer = setTimeout(() => {
      if (wantConnect) {
        addMeta("尝试自动重连...");
        connect();
      }
    }, 1500);
  }

  function disconnect(){
    wantConnect = false;
    if(reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
    if(ws){
      try{ ws.close(); }catch(_){}
      ws = null;
    }
    enableSendIfReady();
  }

  function send(text){
    if(!ws || ws.readyState !== WebSocket.OPEN){
      addMeta("尚未连接，无法发送");
      return;
    }
    if(!currentRoom){
      addMeta("请先输入房间号并点击“进入房间”");
      return;
    }
    if(!text) return;
    const sender = nickname || "匿名";
    ws.send(text);
    addMsg(sender, text, true);
    inputEl.value = "";
    inputEl.focus();
  }

  // 事件绑定
  if (connectBtn) connectBtn.addEventListener("click", () => { wantConnect = true; connect(); });
  if (disconnectBtn) disconnectBtn.addEventListener("click", disconnect);

  // “进入房间”
  if (roomBtn) roomBtn.addEventListener("click", () => {
    const r = roomInput ? roomInput.value.trim() : "";
    if (!r) { addMeta("请输入房间号"); return; }
    currentRoom = r;
    wantRoom = r;
    localStorage.setItem('roomId', currentRoom);
    addMeta("已选择房间：" + currentRoom);
    if (ws && ws.readyState === WebSocket.OPEN) {
      try { ws.send("JOIN:" + currentRoom); } catch(_) {}
      addMeta(`加入房间：${currentRoom}`);
    } else {
      addMeta("未连接，稍后将自动加入该房间");
    }
    enableSendIfReady();
    inputEl.focus();
  });

  if (sendBtn) sendBtn.addEventListener("click", () => {
    send(inputEl.value.trim());
  });

  if (inputEl) inputEl.addEventListener("keydown", (e) => {
    if(e.key === "Enter"){
      e.preventDefault();
      send(inputEl.value.trim());
    }
  });

  document.querySelectorAll(".tools button[data-cmd]").forEach(btn => {
    btn.addEventListener("click", () => {
      const cmd = btn.getAttribute("data-cmd");
      send(cmd);
    });
  });

  // 初始：自动连接，直到用户主动断开
  wantConnect = true;
  connect();
  // 初始根据状态禁用输入
  inputEl.disabled = true;
  sendBtn.disabled = true;
})();